package roleperms

import (
	"database/sql/driver"
	"encoding/json"
	"fmt"
	"gohub/app/models"
	"gohub/pkg/database"
)

// 自定义类型处理JSON数组
type StringArray []string

type RolePermssion struct {
	models.BaseModel

	RoleId string      `json:"roleid,omitempty"`
	Data   StringArray `json:"data,omitempty"`

	models.CommonTimestampsField
}

// func (Role) TableName() string {
// 	return "admin_roles"
// }

func (rolePermModel *RolePermssion) Create() {
	database.DB.Create(&rolePermModel)
}

func (rolePermModel *RolePermssion) Save() (rowsAffected int64) {
	result := database.DB.Save(&rolePermModel)
	return result.RowsAffected
}

func (c *StringArray) Scan(value interface{}) error {
	bytes, ok := value.([]byte)
	if !ok {
		return fmt.Errorf("无法解析子权限数据")
	}
	return json.Unmarshal(bytes, c)
}

func (c StringArray) Value() (driver.Value, error) {
	return json.Marshal(c)
}
